import React, { createContext, useContext, useState, ComponentType, Component } from 'react'

export interface HomeDataInteface {
    homeData: {
        markerCategories: {
            running: boolean | undefined,
            warning: boolean | undefined,
            inMaintenance: boolean | undefined,
            rescueSite: boolean | undefined,
            rescuedToday: boolean | undefined
        },
        filter?: {
            deviceAgeLeft: number | undefined,
            deviceAgeRight: number | undefined,
            deviceClass: string | undefined,
            region: string | undefined,
            suitablePlace: string | undefined
        } | undefined
    }
}

export interface HomeContext {
    homeContext: HomeDataInteface | null,
    setHomeContext: React.Dispatch<React.SetStateAction<HomeDataInteface>> | (() => Error)
}

const context: HomeContext = {
    homeContext: null,
    setHomeContext: () => new Error('setHomeContext is not init')
}
const HomeContext = createContext(context);

export function useHomeContext() {
    return useContext(HomeContext);
}

const HomeContextWarper = ({ children }: {
    children: JSX.Element
}) => {
    const [homeContext, setHomeContext] = useState<HomeDataInteface>({
        homeData: {
            markerCategories: {
                running: true,
                warning: true,
                inMaintenance: true,
                rescueSite: true,
                rescuedToday: true
            },
            filter: {
                deviceAgeLeft: 6,
                deviceAgeRight: 6,
                deviceClass: '',
                region: "巴城镇",
                suitablePlace: "其他"
            }
        }
    })

    return (
        <HomeContext.Provider value={{ homeContext, setHomeContext }}>
            {children}
        </HomeContext.Provider>
    )
}

export function initHomeContext(Home: ComponentType) {
    return class NewHome extends Component {
        render() {
            return (
                <HomeContextWarper>
                    <Home {...this.props} />
                </HomeContextWarper>
            )
        }
    }
}

export default HomeContext